<template>
  <div>
    <el-form ref="pram" :model="pram" :rules="rules" label-width="100px" @submit.native.prevent>
      <div style="display:flex;justify-content: space-around;">
        <el-form-item label="年度" prop="year" class="dislabel">
          <el-select v-model="pram.year" placeholder="年度" clearable style="width: 100px">
            <el-option
              :key="0"
              :label="pram.year"
              :value="pram.year"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="总成绩" prop="trainDesc" class="dislabel">
          <el-select v-model="pram.trainDesc" placeholder="总成绩" clearable style="width:300px;">
            <el-option
              v-for="(item,index) in categoryData.trainDescList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-button icon="el-icon-circle-plus" size="mini" type="primary" @click.native="handlerOpenInfo(0)" style="height:35px;" v-hasPermi="['admin:person:train:save']">新增</el-button>
        <el-button icon="el-icon-download" size="mini" type="primary" @click="handlerExport()"  style="height:35px;">批量导出</el-button>
      </div>

      <el-table :data="pram.trainList" size="mini" :header-cell-style=" {fontWeight:'bold'}" border>
        <!--        <template slot="empty"><span>暂无数据</span></template>-->
        <el-table-column label="训练项目" prop="trainObjectText" min-width="100" align="center"/>
<!--        <el-table-column label="及格标准" prop="trainStandard" min-width="100" align="center"/>-->
<!--        <el-table-column label="表现" prop="trainPerform" min-width="200" align="center"/>-->
        <el-table-column label="分数" prop="trainScore" min-width="100" align="center"/>
        <el-table-column label="评级" prop="trainLevelText" min-width="100" align="center"/>
        <el-table-column label="操作" width="190"  fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handlerOpenInfo(1,scope.row,scope.$index)" v-hasPermi="['admin:person:train:info']">修改</el-button>
            <el-button type="danger" size="mini" @click="handlerInfoDel(scope.$index,scope.row)" v-hasPermi="['admin:person:train:delete']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-form-item class="btn-box">
        <el-button type="primary" @click="handlerSubmit('pram')" v-hasPermi="['admin:person:train:update','admin:person:train:save']">{{ isCreate===0?'确定':'更新' }}</el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      :visible.sync="editDialogConfig.visible"
      :title="editDialogConfig.isCreate === 0? '新增军事训练综合评定':'新增军事训练综合评定'"
      destroy-on-close
      :close-on-click-modal="false"
      :append-to-body="true"
      width="700px"
    >
      <edit
        v-if="editDialogConfig.visible"
        :is-create="editDialogConfig.isCreate"
        :edit-data="editDialogConfig.editData"
        :edit-key="editDialogConfig.editKey"
        :all-category-data="categoryData"
        @hideInfoDialog="hideInfoDialog"
        @assignEditSaveAndHideEditDialog="assignEditSaveAndHideEditDialog"
        @assignEditEditAndHideEditDialog="assignEditEditAndHideEditDialog"
      />
    </el-dialog>
  </div>
</template>

<script>
import * as personApi from '@/api/person.js'
import {Debounce} from '@/utils/validate'
import edit from './edit'
import { createFile } from '@/utils/utils'
export default {
  components: { edit },
  props: {
    isCreate: {
      type: Number,
      required: true
    },
    editData: {
      type: Object,
      default: () => {
        return { rules: [] }
      }
    },
    allCategoryData: {
      type: Object
    },
    allYear:{
      type: Number,
      required: true
    }
  },
  data() {
    return {
      constants:this.$constants,
      pram: {
        year:null,
        trainDesc:null,
        trainList: [],
        personId:0,
        isCreate:null,

        //编辑额外
        trainAdd:[],
        trainRemove:'',
        trainEdit:[],
      },
      rules: {
        year: [{ required: true, message: '请选择年份', trigger: ['blur', 'change'] }],
        trainDesc: [{ required: true, message: '请选择总成绩', trigger: ['blur', 'change'] }],
      },
      editDialogConfig: {
        visible: false,
        isCreate: 0, // 0=创建，1=编辑
        editData: {},
        editKey: -1,
      },
      categoryData:{
        trainDescList:[]
      },
    }
  },
  mounted() {
    this.initEditData()
  },
  methods: {
    close() {
      this.$emit('hideInfoDialog')
    },

    initEditData() {
      this.pram.year = this.allYear
      this.categoryData = this.allCategoryData

      //if (this.isCreate !== 1) return //编辑
      const { trainDesc, trainList, id} = JSON.parse(JSON.stringify(this.editData)) //通过list中slot-scope=“scope“，scope.$index就是该行的下标，scope.row就是该行的数据所有消息对象，有了这两个参数就可以实现编辑、删除功能（this.editData就是scope.row传入的对象参数）

      this.pram.trainDesc = trainDesc===0?null:trainDesc
      this.pram.trainList = trainList||[]
      this.pram.personId = id

      this.pram.trainAdd = []
      this.pram.trainRemove = ''
      this.pram.trainEdit = []
    },
    //导出
    handlerExport() {
      let loading = this.$loading({
        lock: true,
        text: "导出中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      const _pram = {personId: this.pram.personId}
      personApi.exportRoster(_pram)
        .then((res) => {
          if(!createFile(res,'军事训练统计')){
            this.$message.success("未知的文件格式");
          }

          loading.close();
        })
        .catch((res) => {
          loading.close();
        });
    },
    handlerSubmit:Debounce(function(form) {
      this.$refs[form].validate(valid => {
        if (!valid) return
        this.handlerEdit()
      })
    }),
    handlerEdit() {
      this.pram.trainAdd=this.pram.trainList.filter(item=>!item.id)
      this.pram.trainRemove = this.pram.trainRemove.substring(0,this.pram.trainRemove.length - 1)
      this.pram.isCreate = this.isCreate

      personApi.trainAdd(this.pram).then(data => {
        this.$message.success('编辑个人军事训练综合评定成功')
        this.$emit('assignInfoEditAndHideInfoDialog')
      })
    },

    // 职位新增
    handlerOpenInfo(isCreate, editDate, editKey) {
      this.editDialogConfig.editData = editDate
      this.editDialogConfig.isCreate = isCreate
      this.editDialogConfig.visible = true
      this.editDialogConfig.editKey = editKey
    },
    hideInfoDialog() {
      this.editDialogConfig.visible = false
    },
    assignEditSaveAndHideEditDialog(data) {
      setTimeout(() => {
        this.pram.trainList.push(data);
        this.editDialogConfig.visible = false
      }, 200);
    },
    assignEditEditAndHideEditDialog(data,key) {
      setTimeout(() => {
        this.$set(this.pram.trainList,key,data) //更新数组中指定下标的元素

        if (this.isCreate === 1 && data.id){
          //原有数据的编辑
          this.pram.trainEdit.push(data)
        }
        this.editDialogConfig.visible = false
      }, 200);
    },
    handlerInfoDel(key,row){
      //删除单行简历数据
      const  _xKey = key
      this.pram.trainList.splice(_xKey,1);//index 当前元素索引；1：需要删除的元素个数
      //data=data.filter(item=>item.name!='张三');

      if (this.isCreate === 1 && row.id) {
        //编辑时的删除，记录删除ID
        const delId = row.id

        this.pram.trainEdit=this.pram.trainEdit.filter(item=>item.id!==delId)
        //this.pram.familyEdit.splice(_xKey,1)//从编辑项中剔除，直接删除
        this.pram.trainRemove+=delId+','
      }
    },

  }
}
</script>

<style scoped lang="scss">
  .position-btn{
    float:right;
  }
  .btn-box{
    margin-top:20px;
  }
  .dislabel{
    ::v-deep.el-form-item__label{
      width:70px!important;
    }
    ::v-deep.el-form-item__content{
      margin-left:70px!important;
    }
    ::v-deep.el-input--small .el-input__inner,
    ::v-deep.el-input--medium .el-input__inner{
      height:36px;
      line-height:36px;
      font-size:12px;
    }
    ::v-deep.el-textarea__inner{
      font-size:12px;
    }

  }
</style>
